package com.huang825172.sbog.BaseFlux;

import com.huang825172.sbog.BaseFlux.Action.BaseAction;
import com.huang825172.sbog.BaseFlux.Store.BaseStore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//Flux结构之Dispatcher
public class Dispatcher {
    private static volatile Dispatcher dispatcher;
    private Map<String, List<BaseStore>> mStoreMap;

    public static Dispatcher getSingleton() {
        if (dispatcher == null) {
            synchronized (Dispatcher.class) {
                if (dispatcher == null) {
                    dispatcher = new Dispatcher();
                }
            }
        }
        return dispatcher;
    }

    private Dispatcher() {
        mStoreMap = new HashMap<>();
    }

    //注册新的Store
    public void register(BaseStore store) {
        if (store == null) {
            return;
        }
        List<String> labels = store.getActionLabels();
        for (String label : labels) {
            List<BaseStore> stores = mStoreMap.get(label);
            if (stores == null) {
                stores = new ArrayList<>();
                mStoreMap.put(label, stores);
            }
            if (stores.contains(store)) {
                continue;
            }
            stores.add(store);
        }
    }

    public void unregister(BaseStore store) {
        if (store == null) {
            return;
        }
        List<String> labels = store.getActionLabels();
        for (String label : labels) {
            if (!mStoreMap.containsKey(label)) {
                continue;
            }
            List<BaseStore> baseStores = mStoreMap.get(label);
            if (baseStores.remove(store)) {
                if (baseStores.isEmpty()) {
                    mStoreMap.remove(label);
                }
            }
        }
    }

    //分发Action
    public void dispatch(BaseAction action) {
        final String label = action.getLabel();
        final List<BaseStore> stores = mStoreMap.get(label);
        if (stores == null) {
            return;
        }
        for (BaseStore store : stores) {
            store.changeData(action);
            //store.notifyDataChanged(label);
        }
    }
}

